<template>
  <div>
    <el-table
      ref="layoutTable"
      :data="media.layoutSwitchInfo.chs"
      style="width: 100%"
      @row-click="handleCurrentChanges"
      highlight-current-row
    >
      <el-table-column label="ID" prop="index"></el-table-column>
      <el-table-column  :label="$t('message.medias.mode')" align="center">
        <template  slot-scope="scope">   
          <span>{{scope.row.mode? $t(`message.medias.${scope.row.mode}`) : '' }}</span>
        </template> 
      </el-table-column>
    </el-table>
    <setForm id="1" v-show="show">
      <template slot="boxTop">{{$t('message.medias.mode')}}</template>
      <template slot="boxMain">
        <el-row class="row-height">
          <el-col :span="4">   
            <div class="span3" style="marginTop:10px;">            
            <span>{{ $t('message.medias.mode') }}</span>
            </div>
          </el-col>
          <el-col :span="18">  
            <div class="span17"> 
              <el-radio-group v-model="currentRow.mode" @change="onModeChange">
                <el-radio label="manual">{{ $t('message.medias.manual') }}</el-radio>
                <el-radio label="automatic">{{ $t('message.medias.automatic') }}</el-radio>
              </el-radio-group>
            </div>
          </el-col>
        </el-row>
        <el-row class="row-height">
          <el-col :span="4">  
            <div class="span3"> 
              <span style="marginTop:15px;">{{ $t('message.medias.jitterTime') }}</span>
            </div>
          </el-col>
          <el-col :span="18">  
            <div class="span17"> 
              <el-input v-model="currentRow.jitterTime" placeholder></el-input>
            </div>
          </el-col>
        </el-row>
        <el-button v-show="currentRow.mode == 'automatic'" class="btnsave" :disabled="!showChangeModeBtn && !system.isSpecialType" @click="onSave">{{$t('message.save')}}</el-button>
      </template>
    </setForm>
    <setForm id="2" v-if="showManual">
      <template slot="boxTop">{{$t('message.medias.manual')}}</template>
      <template slot="boxMain">
        <el-row>
          <el-col :span="4">
            <span>{{ $t('message.medias.layout') }}</span>
          </el-col>
          <el-col :span="4">
            <el-select
              v-model="currentRow.layoutID"
              :placeholder="$t('message.medias.plsSelect')"
              @change="onLayoutChange"
            >
              <el-option
                v-for="(option, index) in constLayouts"
                :key="index"
                :label="option.id"
                :value="option.id"
              ></el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="2">
            <span>{{ $t('message.medias.local') }}</span>
            <div
              class="stream"
              v-for="(item, index) in media.inputChannel.cnt"
              :key="index"
              draggable="true"
              @click="onSrcClick('local', index)"
            >{{ index + '' }}</div>
          </el-col>
          <el-col :span="2">
            <span>{{ $t('message.medias.remote') }}</span>
            <div
              class="stream"
              v-for="(item, index) in media.streamPullInfo.maxPullCh"
              :key="index"
              draggable="true"
              @click="onSrcClick('remote', index)"
            >{{ index + '' }}</div>
          </el-col>
          <el-col :span="12">
            <div class="layout-preview" id="preview" @dragover="onDragOver" @drop="onDrop"></div>
          </el-col>
        </el-row>
        <el-button class="btnsave" v-if="true" @click="onSaveManual">{{$t('message.save')}}</el-button>
      </template>
    </setForm>
    <setForm id="3" v-if="showAutomatic">
      <template slot="boxTop">{{$t('message.medias.automatic')}}</template>
      <template slot="boxMain">
        <el-row>
          <el-col :span="4">
            <span>{{ $t('message.medias.layoutDetail') }}</span>
          </el-col>
          <el-col :span="12">
            <div class="layout-preview" id="preview" @dragover="onDragOver" @dragend="onDrop"></div>
          </el-col>
        </el-row>
      </template>
    </setForm>
    <setForm id="3" v-if="showAutoLayoutSetting">
      <template slot="boxTop">{{$t('message.medias.autoLayoutSetting')}}</template>
      <template slot="boxMain">
        <el-table :data="defaultLayouts" style="width: 100%" highlight-current-row>
          <el-table-column :label="$t('message.medias.screenNum')" prop="screenNum"></el-table-column>
          <el-table-column :label="$t('message.medias.layoutName')">
            <template slot-scope="scope">
              <span>{{ showLayoutName(scope.row.layoutID) }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" :label="$t('message.operation')" width="100">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="editBindLayout(scope.row)"
              >{{$t('message.medias.edit')}}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </setForm>
    <el-dialog :visible.sync="showDialog" :title="$t('message.medias.selectLayout')" @open="onDialogOpen">
      <div>
        <el-row>
          <el-col :span="4">
            <span>{{ $t('message.medias.layout') }}</span>
          </el-col>
          <el-col :span="16">
            <el-select
              v-model="dialogData.dialogLayoutId"
              :placeholder="$t('message.medias.plsSelect')"
              @change="onDialogOpen"
            >
              <el-option
                v-for="(option, index) in constLayouts"
                :key="index"
                :label="option.id"
                :value="option.id"
              ></el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <span>{{ $t('message.medias.layoutDetail') }}</span>
          </el-col>
          <el-col :span="16">
            <div class="layout-preview" id="dialog-preview"></div>
          </el-col>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showDialog = false">{{ $t('message.cancel') }}</el-button>
        <el-button type="primary" @click="onSelectLayout">{{ $t('message.ok') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { api } from "../../../../libs/api";
import setForm from "@/components/setForm";
import mylist from "@/components/MyList";
import ebus from "../../../../libs/ebus";
import { mapState } from "vuex";
import { VLayout } from "@/libs/layout.js";
import topTable from "../../../../components/topTable";
import _ from "lodash";
import { setTimeout } from "timers";
import { LcdPreview } from "@/libs/canvas.js";
import store from "@/store/index";
export default {
 async created() {
   await ebus.emit("getLayoutSwitchInfo", this);
   ebus.emit("getStremPullInfo", this);
    this.getLayouts();
     
  },
  mounted() {
    let timeout = 0;
      this.timer = setInterval(() => {
      timeout++
      if(this.media.layoutSwitchInfo.chs.length > 0) {
        if(this.system.isSpecialType) {
           this.initdata(this.media.layoutSwitchInfo.chs[0],0)
        }else {
          this.initdata(this.media.layoutSwitchInfo.chs[1],1)
        }
        clearInterval(this.timer)
      }else if (timeout > 8){
         clearInterval(this.timer)
      }
      },300)
    
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  computed: {
    ...mapState(["media","system"]),
    showManual() {
      return this.isList && this.currentRow.mode === "manual";
    },
    showAutomatic() {
      return this.isList && this.currentRow.mode === "automatic";
    },
    showAutoLayoutSetting() {
      return this.isList && this.currentRow.mode === "automatic" && (this.currentRow.index || this.system.isSpecialType);
    },
    showChangeModeBtn() {
      return this.isList && this.currentRow.index;
    },
    curTopic() {
      if (this.system.isSpecialType) {
        return "mediaapp";
      } else {
        return "zhishen";
      }
    },
  },
  data() {
    return {
      curLayout: {
        base: {
          h: 1920,
          v: 1080
        }
      },
      timer: null,
      windowList: [],
      dialogData: {
        dialogLayoutId: "",
        screenNum: 0
      },
      showDialog: false,
      preview: new LcdPreview(),
      dialogPreview: new LcdPreview(),
      multiScreenX: 1,
      multiScreenY: 1,
      checked: true,
      oldId:-1,
      constLayouts: [
        {
          id: "fullScreen",
          name: "全屏",
          layoutType: "constant",
          base: {
            h: 1920,
            v: 1080
          },
          subScreen: [
            {
              left: 0,
              top: 0,
              right: 1920,
              bottom: 1080
            }
          ]
        },
        {
          id: "splitScreenBy2",
          name: "二分屏",
          layoutType: "constant",
          base: {
            h: 1920,
            v: 1080
          },
          subScreen: [
            {
              left: 0,
              top: 0,
              right: 960,
              bottom: 1080
            },
            {
              left: 960,
              top: 0,
              right: 1920,
              bottom: 1080
            }
          ]
        }
      ],
      currentRow: {
        index: 0,
        mode: "manual",
        jitterTime: 0,
        layoutID: "",
        srcList: []
      },
      show: false,
      isList: false,
      defaultLayouts: [
        {
          screenNum: 1,
          id: "fullScreen"
        },
        {
          screenNum: 2,
          id: "splitScreenBy2"
        },
        {
          screenNum: 3,
          id: "fullScreen"
        },
        {
          screenNum: 4,
          id: "splitScreenBy2"
        },
        {
          screenNum: 5,
          id: "fullScreen"
        },
        {
          screenNum: 6,
          id: "splitScreenBy2"
        },
        {
          screenNum: 7,
          id: "fullScreen"
        }
      ]
    };
  },
  components: {
    setForm,
    mylist,
    topTable
  },
  methods: {
    initdata(row,index) {
      this.$refs.layoutTable.setCurrentRow(row);
      this.handleCurrentChanges(row, index) 
    },
    handleCurrentChanges(val, index) {
        
      this.curLayout = {};
      
      var currentRow = this.currentRow;
      for (var key in val) {
        currentRow[key] = val[key];
      }
     
      if (val.mode === "manual") {
        
        this.getManualLayoutInfo(currentRow.index);
      } else if (val.mode === "automatic") {
        this.getAutoLayoutInfo(currentRow.index);
      }
      this.show = val.index === 0 && !this.system.isSpecialType ? false : true;
      this.isList=true;
    },
   async onSave(noMsg) {
     let that = this;
      var option = {
        mode: this.currentRow.mode,
        jitterTime: this.currentRow.jitterTime
      };
     await api.onRequest(
        `$method.$set.${this.curTopic}.layoutSwitch.ch.${this.currentRow.index}.cfg`,
        JSON.stringify(option),
        null,
        null,
        function(message, reqReply) {
          var res = JSON.parse(message);
          if (res.code == 0) {
            if(noMsg == 'savemanual') {
            }else {
              this.notification("Success", "");
              this.show = false;
              this.isList = false;
            }
            ebus.emit("getLayoutSwitchInfo", this);
            
            
          } else {
            that.isListCodeMsg(res.code, this, res.msg);
          }
        }.bind(this)
      );
    },
    init() {
      this.currentRow = {
        index: 0,
        locals: [
          {
            checked: false
          },
          {
            checked: false
          },
          {
            checked: false
          },
          {
            checked: false
          },
          {
            checked: false
          },
          {
            checked: false
          }
        ],
        remotes: [
          {
            checked: false
          },
          {
            checked: false
          },
          {
            checked: false
          },
          {
            checked: false
          },
          {
            checked: false
          },
          {
            checked: false
          }
        ]
      };
    },
    onLayoutChange(val) {
      this.curLayout = _.find(this.constLayouts, item => {
        return item.id === val;
      });
      this.draw(this.curLayout);
    },
    draw(val) {
      var preview = document.getElementById("preview");
      var offsetW = preview.offsetWidth;
      var offsetH = preview.offsetHeight;
      var multiScreenX = this.multiScreenX;
      var multiScreenY = this.multiScreenY;
      var maxCount = 256;
      // var scale = 1
      if (multiScreenX * multiScreenY * 16 < 256) {
        maxCount = this.multiScreenX * this.multiScreenY * 16;
      }

      let xScale = offsetW / this.curLayout.base.h;
      let yScale = offsetH / this.curLayout.base.v;

      var windowList = this.windowList;
      windowList = [];
      if (val && val.subScreen && val.subScreen.length) {
        val.subScreen.forEach((item, index) => {
          // var srcName = '';
          // if (srcList && srcList[index]) {
          //   srcName = srcList[index]
          // }
          if (item.left || item.top || item.right || item.bottom) {
            windowList.push({
              windowId: index,
              layer: index,
              playAudio: item.playAudio,
              playVedio: item.playVideo,
              srcName: item.srcName,
              coordinate: {
                left: item.left,
                top: item.top,
                right: item.right,
                bottom: item.bottom
              }
            });
          }
        });
      }

      this.preview.init("preview", {
        width: offsetW,
        height: offsetH,
        multiScreenX: multiScreenX,
        multiScreenY: multiScreenY,
        maxWindowCnt: maxCount,
        windowList: windowList || []
      });
      this.preview.updateBg({
        color: {
          hex: "#666"
        }
      });

      this.preview.updateWindows(windowList, {
        xScale: xScale,
        yScale: yScale
      });
    },
    onDragOver(event) {
      event.preventDefault();
      console.log("onDropOver");
    },
    onDrop(e) {
      // this.preview.setMode('newWindow')
      console.log("drop");
    },
    editBindLayout(row) {
      this.dialogData.dialogLayoutId = row.layoutID;
      this.dialogData.screenNum = row.screenNum;
      this.isListDialog = true;
    },
    showLayoutName(id) {
      var res = _.find(this.constLayouts, item => {
        return item.id === id;
      });

      if (res) {
        return res.id;
      } else {
        return "";
      }
    },
    onSelectLayout() {
      var defaultLayouts = this.defaultLayouts;
      _.forEach(defaultLayouts, item => {
        if (item.screenNum === this.dialogData.screenNum) {
          item.layoutID = this.dialogData.dialogLayoutId;
        }
      });
      api.onRequest(
        `$method.$set.${this.curTopic}.layoutSwitch.ch.${
          this.currentRow.index
        }.layoutList`,
        JSON.stringify({
          layoutList: defaultLayouts
        }),
        null,
        null,
        (message, reqReply) => {
          var res = JSON.parse(message);
          if (res.code == 0) {
            this.notification("Success", "");
            this.isListDialog = false;
          } else {
            this.isListCodeMsg(res.code, this, res.msg);
          }
        }
      );      
    },
    onDialogOpen() {
      setTimeout(() => {
        this.drawDialogLayout();
      }, 100);
    },
    drawDialogLayout() {
      var preview = document.getElementById("dialog-preview");
      var offsetW = preview.offsetWidth;
      var offsetH = preview.offsetHeight;
      var multiScreenX = this.multiScreenX;
      var multiScreenY = this.multiScreenY;
      var maxCount = 256;
      if (multiScreenX * multiScreenY * 16 < 256) {
        maxCount = this.multiScreenX * this.multiScreenY * 16;
      }
      
      var layout = _.find(this.constLayouts, item => {
        return item.id === this.dialogData.dialogLayoutId;
      });
      let xScale = offsetW / layout.base.h;
      let yScale = offsetH / layout.base.v;

      this.dialogPreview.init("dialog-preview", {
        width: offsetW,
        height: offsetH,
        multiScreenX: multiScreenX,
        multiScreenY: multiScreenY,
        maxWindowCnt: maxCount
      });
      this.dialogPreview.updateBg({
        color: {
          hex: "#666"
        }
      });
      var windowList = [];

      if (layout && layout.subScreen) {
        layout.subScreen.forEach((item, index) => {
          if (item.left || item.top || item.right || item.bottom) {
            windowList.push({
              windowId: index,
              layer: index,
              coordinate: {
                left: item.left,
                top: item.top,
                right: item.right,
                bottom: item.bottom
              }
            });
          }
        });
      }

      if (windowList && windowList.length > 0) {
        this.dialogPreview.updateWindows(windowList, {
          xScale: xScale,
          yScale: yScale
        });
      }
    },
    getLayouts() {
      api.onRequest(
        `$method.$query.${this.curTopic}.layout.cfg`,
        JSON.stringify({}),
        null,
        null,
        function(message, reqReply) {
          var res = JSON.parse(message);
          if (res.code == 0) {
            this.constLayouts.splice(0, this.constLayouts.length);
            res.data.items.forEach(item => {
              this.constLayouts.push(item);
            });
          }
        }.bind(this)
      );
    },
    getManualLayoutInfo(index) {
      api.onRequest(
        `$method.$get.${this.curTopic}.layoutSwitch.ch.${index}.manual`,
        null,
        null,
        null,
        function(message, reqReply) {
          var res = JSON.parse(message);
          if (res.code == 0) {
            // console.log('siteName',this.media.streamPullInfo)
            this.currentRow.layoutID = res.data.layoutID;
            this.oldId = res.data.layoutID;
            this.currentRow.srcList = res.data.srcList;
            this.curLayout = _.find(this.constLayouts, item => {
              return item.id === this.currentRow.layoutID;
            });
            var srcList = res.data.srcList;
            if (this.curLayout && this.curLayout.subScreen && this.curLayout.subScreen.length){
              this.curLayout.subScreen.forEach((item, idx) => {
                item.srcName = srcList[idx].srcAddr;
                item.playVideo = srcList[idx].playVideo;
                item.playAudio = srcList[idx].playAudio;
              });
            }
            
            if (this.curLayout && this.curLayout.subScreen) {
              setTimeout(() => {
                this.draw(this.curLayout, this.currentRow.srcList);
              }, 100);
            }
          }
        }.bind(this)
      );
    },
    getAutoLayoutInfo(index) {
      this.defaultLayouts = [];
      api.onRequest(
        `$method.$get.${this.curTopic}.layoutSwitch.ch.${index}.auto`,
        null,
        null,
        null,
        (message, reqReply) => {
          var res = JSON.parse(message);
          if (res.code == 0) {
            this.currentRow.layoutID = res.data.layoutID;
            this.currentRow.srcList = res.data.srcList;
            this.curLayout = _.find(this.constLayouts, item => {
              return item.id === this.currentRow.layoutID;
            });
            var srcList = res.data.srcList;
            if (this.curLayout && this.curLayout.subScreen && this.curLayout.subScreen.length){
              this.curLayout.subScreen.forEach((item, idx) => {
                item.srcName = srcList[idx].srcAddr;
                item.playVideo = srcList[idx].playVideo;
                item.playAudio = srcList[idx].playAudio;
              });
            }
            if (this.curLayout && this.curLayout.subScreen) {
              setTimeout(() => {
                this.draw(this.curLayout);
              }, 100);
            }
          }
        }
      );

      api.onRequest(
        `$method.$get.${this.curTopic}.layoutSwitch.ch.${index}.layoutList`,
        null,
        null,
        null,
        (message, reqReply) => {
          var res = JSON.parse(message);
          if (res.code == 0) {
            this.defaultLayouts = res.data.layoutList;
          }
        }
      );
    },
    async onSaveManual() {
      await this.onSave('savemanual');
      var selectCnt = 0;
      var cfg = this.preview.getUserCfg();
      _.forEach(cfg.windowList, item => {
        if (item.srcName) {
          selectCnt ++;
        }
      })
      
      if (selectCnt > 7) {
        this.notification('error', this.$t('message.medias.openWindowLimit'))
        return
      }
      var srcList = [];
      for (var i = 0; i < 9; i++) {
        srcList.push({
          srcAddr: "",
          playAudio: true,
          playVideo: true,
          screenID: i
        });
      }
      _.forEach(cfg.windowList, (item, index) => {
        srcList[index].srcAddr = item.srcName || '';
      });
      var option = {
        layoutID: this.currentRow.layoutID,
        srcList: srcList
      };
      api.onRequest(
        `$method.$set.${this.curTopic}.layoutSwitch.ch.${this.currentRow.index}.manual`,
        JSON.stringify(option),
        null,
        null,
        function(message, reqReply) {
          var res = JSON.parse(message);
          if (res.code == 0) {
            this.notification("Success", "");
            if(this.oldId !== this.currentRow.layoutID) {
               _.forEach(this.constLayouts, item => {
                if(item.id == this.oldId) {
                  _.forEach(item.subScreen, item1 => {
                    item1.srcName = '';
                    item.playVideo = false;
                    item.playAudio =false;
                  })
                }
              })
            }
           
            this.getManualLayoutInfo(this.currentRow.index);

          } else {
            this.isListCodeMsg(res.code, this, res.msg);
          }
        }.bind(this)
      );
    },
    onSrcClick(type, index) {
      this.$store.dispatch("media/setSrcName", type + ":" + index);
      window.localStorage.setItem("srcName:", type + ":" + index);
    },
    onModeChange() {
      this.draw(this.curLayout);
    }
  }
};
</script>

<style scoped>
.row-height {
  height: 40px;
  margin-bottom: 10px;
}
.layout-preview {
  height: 400px;
}
.el-col .position {
  width: 100%;
}
/* .preview, #dialog-preview {
  height: 400px;
  width: 200px;
} */
.stream {
  width: 80%;
  height: 50px;
  border: 1px solid #409eff;
  margin-top: 5px;
}
</style>

